package blog.open1111.controller.admin;

import blog.open1111.entity.Article;
import blog.open1111.entity.PageBean;
import blog.open1111.service.ArticleService;
import blog.open1111.service.impl.InitComponent;
import blog.open1111.util.ResponseUtil;
import blog.open1111.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dengwubo on 2017/9/12.
 */
@RequestMapping("/admin/article")
@SuppressWarnings("all")
@Controller
public class ArticleAdminController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private InitComponent initComponent;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false); // 严格解析
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }


    @RequestMapping("/list")
    public String list(@RequestParam(value="page",required=false)String page, @RequestParam(value="rows",required=false)String rows,
                       Article s_article, HttpServletResponse response) throws Exception{
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("title", StringUtil.formatLike(s_article.getTitle()));

        List<Article> articleList = articleService.list(map);
        Long total = articleService.getTotal(map);
        JSONObject result = new JSONObject();
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONArray jsonArray = JSONArray.fromObject(articleList, config);
        System.out.println("jsonArray.size()======================="+jsonArray.size());
        System.out.println("total================"+total);
        result.put("rows",jsonArray);
        result.put("total",total);
        ResponseUtil.write(response,result);
        return null;
    }

    @RequestMapping("/save")
    public String save(Article article,HttpServletResponse response)throws Exception{
        int resultTotal=0;
        if (article.getId()==null){
            article.setReleaseDate(new Date());
            resultTotal = articleService.add(article);
        }else{
            if (article.getState()==1)
                article.setReleaseDate(new Date());

            else
                article.setReleaseDate(null);

            resultTotal= articleService.update(article);

        }
        JSONObject result = new JSONObject();
        if (resultTotal>0){ // 如果数据库中的数据发生了变化,那么缓存中的数据也应该及时更新
            initComponent.refershSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext());
            result.put("success",true);
        }else{
            result.put("success",false);
        }
        ResponseUtil.write(response,result);

        return null;
    }

    /**
     * 删除帖子信息
     * @param ids
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public String delete(@RequestParam(value = "ids")String ids,HttpServletResponse response) throws Exception{
        String[] idsStr = ids.split(",");
        JSONObject result = new JSONObject();
        Arrays.asList(idsStr).forEach(id->{
            articleService.delete(Integer.parseInt(id));
        });
        initComponent.refershSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext());
        result.put("success",true);
        ResponseUtil.write(response,result);
        return null;
    }

    @RequestMapping("/findById")
    public String findById(@RequestParam(value = "id")Integer id,HttpServletResponse response)throws Exception{
        Article article = articleService.findById(id);
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
        JSONObject result  = JSONObject.fromObject(article,config);
        ResponseUtil.write(response,result);
        return null;
    }


}
